<template>
  <div class="review-manager">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <h2>评价管理</h2>
      <el-tag type="info">共 {{ total }} 条评价</el-tag>
    </div>

    <!-- 搜索和操作区域 -->
    <el-card class="operation-area" shadow="hover">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.productName" placeholder="请输入商品名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable></el-input>
        </el-form-item>
        <el-form-item label="评价状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="不通过" :value="0"></el-option>
            <el-option label="已通过" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="medium" plain type="primary" @click="handleSearch">查询</el-button>
          <el-button size="medium" plain @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>


    </el-card>

    <!-- 评价列表 -->
    <el-card class="table-card" shadow="hover">
      <el-table :data="reviews" border style="width: 100%">
        <!-- <el-table-column type="selection" width="55"></el-table-column> -->
        <el-table-column label="用户信息" width="180">
          <template slot-scope="scope">
            <div class="user-info">
              <div>用户名：{{ scope.row.user.username }}</div>
              <div>姓名：{{ scope.row.user.name }}</div>
              <div v-if="scope.row.isAnonymous === 1" class="anonymous-tag">
                <el-tag size="mini" type="info">匿名评价</el-tag>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品信息" min-width="300">
          <template slot-scope="scope">
            <div class="product-info">
              <el-image 
                :src="scope.row.product.imageUrl?.startsWith('/') ? `/api${scope.row.product.imageUrl}` : `/api/${scope.row.product.imageUrl}`" 
                :preview-src-list="[scope.row.product.imageUrl?.startsWith('/') ? `/api${scope.row.product.imageUrl}` : `/api/${scope.row.product.imageUrl}`]"
                fit="cover"
                style="width: 50px; height: 50px">
              </el-image>
              <div class="product-detail">
                <div class="product-name">{{ scope.row.product.name }}</div>
                <div class="product-price">
                  ¥{{ scope.row.product.price.toFixed(2) }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="评分" width="150">
          <template slot-scope="scope">
            <el-rate
              v-model="scope.row.rating"
              disabled
              show-score
              text-color="#ff9900">
            </el-rate>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="评价内容" min-width="200">
          <template slot-scope="scope">
            <div class="review-content">{{ scope.row.content }}</div>
            <!-- 添加评价图片显示 -->
            <div v-if="scope.row.images" class="review-images-preview">
              <el-image 
                v-for="(img, index) in parseImages(scope.row.images).slice(0, 3)" 
                :key="index"
                :src="img"
                fit="cover"
                class="review-image-item"
                :preview-src-list="parseImages(scope.row.images)">
              </el-image>
              <div v-if="parseImages(scope.row.images).length > 3" class="more-images">
                +{{ parseImages(scope.row.images).length - 3 }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="评价时间" width="180">
          <template slot-scope="scope">
            {{ formatTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column v-if="userInfo.role==='ADMIN'||userInfo.role==='SUPER_ADMIN'" prop="status" label="审核状态" width="120">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
      
              @change="handleStatusChange(scope.row)"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button 
              v-if="userInfo.role==='MERCHANT'"
              type="text"
              size="small" 
              @click="handleReply(scope.row)">回复</el-button>
            <el-button 
              v-if="userInfo.role==='ADMIN'||userInfo.role==='SUPER_ADMIN'"
              type="text"
              class="danger-text"
              size="small" 
              @click="handleDelete(scope.row)">删除</el-button>
            <el-button 
              type="text"
              size="small" 
              @click="handleDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination 
        v-show="total > 0" 
        :total="total" 
        :page.sync="queryParams.currentPage" 
        :limit.sync="queryParams.size" 
        @pagination="getList" />
    </el-card>

    <!-- 添加回复对话框 -->
    <el-dialog title="商家回复" :visible.sync="replyDialogVisible" width="500px">
      <div class="review-detail" v-if="currentReview">
        <div class="review-user">
          <div class="user-name">
            {{ currentReview.isAnonymous === 1 ? '匿名用户' : currentReview.user?.username }}
          </div>
          <div class="review-rating">
            <el-rate v-model="currentReview.rating" disabled show-score text-color="#ff9900"></el-rate>
          </div>
        </div>
        <div class="review-time">{{ formatTime(currentReview.createdAt) }}</div>
        <div class="review-text">{{ currentReview.content }}</div>
        <!-- 添加评价图片显示 -->
        <div v-if="currentReview.images" class="review-images-dialog">
          <el-image 
            v-for="(img, index) in parseImages(currentReview.images)" 
            :key="index"
            :src="img"
            fit="cover"
            style="width: 70px; height: 70px; margin-right: 8px; border-radius: 4px;"
            :preview-src-list="parseImages(currentReview.images)">
          </el-image>
        </div>
      </div>
      <el-form :model="replyForm" :rules="replyRules" ref="replyForm" label-width="80px">
        <el-form-item label="回复内容" prop="merchantReply">
          <el-input type="textarea" v-model="replyForm.merchantReply" :rows="4" placeholder="请输入回复内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="replyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitReply">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加评价详情对话框 -->
    <el-dialog title="评价详情" :visible.sync="detailDialogVisible" width="600px">
      <div class="review-detail-full" v-if="currentReview">
        <div class="detail-section">
          <h4>用户信息</h4>
          <div class="detail-item">
            <span class="label">用户名：</span>
            <span>{{ currentReview.isAnonymous === 1 ? '匿名用户' : currentReview.user?.username }}</span>
          </div>
          <div class="detail-item" v-if="currentReview.isAnonymous !== 1">
            <span class="label">姓名：</span>
            <span>{{ currentReview.user?.name }}</span>
          </div>
          <div class="detail-item">
            <span class="label">是否匿名：</span>
            <span>{{ currentReview.isAnonymous === 1 ? '是' : '否' }}</span>
          </div>
        </div>

        <div class="detail-section">
          <h4>商品信息</h4>
          <div class="product-detail-info">
            <el-image 
              :src="currentReview.product?.imageUrl?.startsWith('/') ? `/api${currentReview.product?.imageUrl}` : `/api/${currentReview.product?.imageUrl}`" 
              :preview-src-list="[currentReview.product?.imageUrl?.startsWith('/') ? `/api${currentReview.product?.imageUrl}` : `/api/${currentReview.product?.imageUrl}`]"
              fit="cover"
              style="width: 80px; height: 80px; border-radius: 4px;">
            </el-image>
            <div class="product-info-right">
              <div class="product-name">{{ currentReview.product?.name }}</div>
              <div class="product-price">
                <span>价格：¥{{ currentReview.product?.price }}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h4>评价内容</h4>
          <div class="detail-item">
            <span class="label">评分：</span>
            <el-rate v-model="currentReview.rating" disabled show-score text-color="#ff9900"></el-rate>
          </div>
          <div class="detail-item">
            <span class="label">评价内容：</span>
            <span>{{ currentReview.content }}</span>
          </div>
          <div class="detail-item">
            <span class="label">评价时间：</span>
            <span>{{ formatTime(currentReview.createdAt) }}</span>
          </div>
          <div class="detail-item" v-if="currentReview.orderId">
            <span class="label">订单ID：</span>
            <span>{{ currentReview.orderId }}</span>
          </div>
          <div class="detail-item" v-if="currentReview.images">
            <span class="label">评价图片：</span>
            <div class="review-images">
              <el-image 
                v-for="(img, index) in parseImages(currentReview.images)" 
                :key="index"
                :src="img"
                fit="cover"
                style="width: 80px; height: 80px; margin-right: 8px; border-radius: 4px;"
                :preview-src-list="parseImages(currentReview.images)">
              </el-image>
            </div>
          </div>
        </div>

        <div class="detail-section" v-if="currentReview && currentReview.merchantReply">
          <h4>商家回复</h4>
          <div class="detail-item">
            <span class="label">回复内容：</span>
            <span>{{ currentReview.merchantReply }}</span>
          </div>
          <div class="detail-item" v-if="currentReview.replyTime">
            <span class="label">回复时间：</span>
            <span>{{ formatTime(currentReview.replyTime) }}</span>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button v-if="userInfo.role==='MERCHANT' && currentReview && !currentReview.merchantReply" type="primary" @click="handleReply(currentReview)">回复评价</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Request from '@/utils/request'
import Pagination from '@/components/Pagination/index.vue'
import { formatTime } from '@/utils/time'
import { NULL } from 'sass';

export default {
  name: 'ReviewManager',
  inject: ['userInfo'],
  components: {
    Pagination
  },
  data() {
    return {
      // 搜索表单
      searchForm: {
        productName: '',
        username: '',
        status: ''
      },
      // 查询参数
      queryParams: {
        currentPage: 1,
        size: 10
      },
      // 评价列表
      reviews: [],
      // 总数
      total: 0,
      // 添加回复对话框
      replyDialogVisible: false,
      currentReview: null,
      replyForm: {
        merchantReply: ''
      },
      replyRules: {
        merchantReply: [
          { required: true, message: '请输入回复内容', trigger: 'blur' },
          { min: 2, max: 500, message: '长度在 2 到 500 个字符', trigger: 'blur' }
        ]
      },
      // 添加详情对话框
      detailDialogVisible: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    formatTime,
    // 获取评价列表
    async getList() {
      try {
        const merchantId = this.userInfo.role==='MERCHANT' ? this.userInfo.id : null
        console.log("merchantId",this.userInfo.id)
        const params = {
          ...this.queryParams,
          ...this.searchForm,
          merchantId
        }
        const res = await Request.get('/review/page', { params })
        if (res.code === '0') {
          this.reviews = res.data.records
          this.total = res.data.total
          
          // 调试评价图片
          if (this.reviews.length > 0) {
            console.log("评价图片示例:", this.reviews[0].images)
            if (this.reviews[0].images) {
              console.log("解析后的图片:", this.parseImages(this.reviews[0].images))
            }
          }
        }
      } catch (error) {
        console.error('获取评价列表失败:', error)
      }
    },
    // 搜索
    handleSearch() {
      this.queryParams.currentPage = 1
      this.getList()
    },
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        productName: '',
        username: '',
        status: ''
      }
      this.handleSearch()
    },
    // 处理状态变更
    async handleStatusChange(row) {
      try {
        const res = await Request.put(`/review/${row.id}/status?status=${row.status}`)
        if (res.code === '0') {
          this.$message.success(`审核${row.status === 1 ? '通过' : '不通过'}成功`)
          this.getList()
        } else {
          // 如果失败，恢复原状态
          row.status = row.status === 1 ? 0 : 1
          this.$message.error('操作失败')
        }
      } catch (error) {
        // 发生错误时恢复原状态
        row.status = row.status === 1 ? 0 : 1
        console.error('更新评价状态失败:', error)
        this.$message.error('操作失败')
      }
    },
    // 删除评价
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该评价?', '提示', {
          type: 'warning'
        })
        const res = await Request.delete(`/review/${row.id}`)
        if (res.code === '0') {
          this.$message.success('删除成功')
          this.getList()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },
    // 处理回复
    handleReply(row) {
      this.currentReview = row
      this.replyForm.merchantReply = row.merchantReply || ''
      this.replyDialogVisible = true
    },
    // 提交回复
    async submitReply() {
      try {
        await this.$refs.replyForm.validate()
        const res = await Request.put(`/review/${this.currentReview.id}/reply?merchantReply=${encodeURIComponent(this.replyForm.merchantReply)}`)
        if (res.code === '0') {
          this.$message.success('回复成功')
          this.replyDialogVisible = false
          this.getList()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('回复失败:', error)
          this.$message.error('回复失败')
        }
      }
    },
    // 查看详情
    handleDetail(row) {
      this.currentReview = row
      this.detailDialogVisible = true
    },
    // 解析图片
    parseImages(images) {
      try {
        if (!images) return []
        
        // 调试输出原始图片字符串
        console.log("原始图片字符串:", images)
        
        let imageArray
        try {
          imageArray = JSON.parse(images)
        } catch (parseError) {
          console.error('JSON解析失败，尝试其他格式:', parseError)
          // 尝试处理可能是字符串数组的情况
          if (typeof images === 'string' && images.includes(',')) {
            imageArray = images.split(',')
          } else {
            imageArray = [images] // 单个图片路径
          }
        }
        
        // 确保是数组
        if (!Array.isArray(imageArray)) {
          imageArray = [imageArray]
        }
        
        // 处理图片路径
        return imageArray.map(img => {
          if (!img) return ''
          
          // 确保img是字符串
          const imgStr = String(img).trim()
          
          // 处理不同的路径格式
          if (imgStr.startsWith('http')) {
            return imgStr
          } else if (imgStr.startsWith('/api')) {
            return imgStr
          } else if (imgStr.startsWith('/')) {
            return `/api${imgStr}`
          } else {
            return `/api/${imgStr}`
          }
        }).filter(img => img) // 过滤掉空路径
      } catch (error) {
        console.error('解析图片失败:', error)
        return []
      }
    }
  }
}
</script>

<style scoped>
.review-manager {
  padding: 24px;
  background-color: #fff8f0;
  min-height: calc(100vh - 60px);
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  font-size: 24px;
  font-weight: 500;
  color: #E67E22;
  margin: 0;
  margin-right: 15px;
}

.operation-area {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
}

.table-card {
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.product-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.product-name {
  font-size: 14px;
  color: #E67E22;
}

.product-price {
  font-size: 13px;
  color: #f56c6c;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 14px;
  color: #606266;
}

.anonymous-tag {
  margin-top: 4px;
}

.review-content {
  color: #606266;
  line-height: 1.5;
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 评价图片预览样式 */
.review-images-preview {
  display: flex;
  margin-top: 8px;
  align-items: center;
}

.review-image-item {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  margin-right: 6px;
  object-fit: cover;
}

.more-images {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

/* 回复对话框中的图片样式 */
.review-images-dialog {
  margin-top: 12px;
  display: flex;
  flex-wrap: wrap;
}

/* 文本按钮样式 */
.success-text {
  color: #F39C12;
}

.success-text:hover {
  color: #E67E22;
}

.danger-text {
  color: #F56C6C;
}

.danger-text:hover {
  color: #f78989;
}

:deep(.el-button--text) {
  padding: 0 8px;
}

:deep(.el-switch__label) {
  color: #606266;
}

:deep(.el-switch.is-checked .el-switch__label--right) {
  color: #F39C12;
}

:deep(.el-switch:not(.is-checked) .el-switch__label--left) {
  color: #ff4949;
}

:deep(.el-switch__label--right) {
  margin-left: 6px;
}

:deep(.el-switch__label--left) {
  margin-right: 6px;
}

/* 回复对话框样式 */
.review-detail {
  background: #fff4e0;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
}

.review-user {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.user-name {
  font-weight: 500;
  color: #E67E22;
}

.review-time {
  color: #909399;
  font-size: 12px;
  margin-bottom: 8px;
}

.review-text {
  color: #606266;
  line-height: 1.6;
}

/* 详情对话框样式 */
.review-detail-full {
  padding: 0 10px;
}

.detail-section {
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f5e8d3;
}

.detail-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.detail-section h4 {
  font-size: 16px;
  color: #E67E22;
  margin: 0 0 16px 0;
  font-weight: 500;
}

.detail-item {
  display: flex;
  margin-bottom: 12px;
  font-size: 14px;
  line-height: 1.4;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-item .label {
  width: 100px;
  color: #909399;
}

.product-detail-info {
  display: flex;
  gap: 16px;
  padding: 16px;
  background: #fff4e0;
  border-radius: 8px;
}

.product-info-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.review-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 8px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: none;
}

:deep(.el-table th) {
  background-color: #fff4e0;
  font-weight: 500;
  color: #E67E22;
  padding: 14px 0;
}

:deep(.el-table td) {
  padding: 14px 0;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fffbf5;
}

:deep(.el-button--primary) {
  background-color: #F39C12;
  border-color: #F39C12;
  color: white;
}

:deep(.el-button--primary:hover) {
  background-color: #E67E22;
  border-color: #E67E22;
  color: white;
}

:deep(.el-pagination) {
  padding: 20px 0;
  text-align: right;
}

:deep(.el-pagination button) {
  background: none;
}

:deep(.el-pagination .btn-next),
:deep(.el-pagination .btn-prev) {
  border: 1px solid #f0d5b3;
  border-radius: 8px;
}

:deep(.el-pager li) {
  border-radius: 8px;
  margin: 0 3px;
}

:deep(.el-pager li.active) {
  background-color: #F39C12;
  color: #fff;
}

:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
}

:deep(.el-dialog__header) {
  padding: 24px;
  border-bottom: 1px solid #f5e8d3;
  margin: 0;
  background: #fff4e0;
}

:deep(.el-dialog__title) {
  font-size: 20px;
  font-weight: 500;
  color: #E67E22;
}

:deep(.el-dialog__body) {
  padding: 32px 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #f5e8d3;
  background: #faf7f0;
}
</style> 